<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="客户编号" prop="customerNo">
        <el-input v-model="formData.customerNo" placeholder="请输入客户编号" />
      </el-form-item>
      <el-form-item label="平台客户ID" prop="platformCustomerId">
        <el-input v-model="formData.platformCustomerId" placeholder="请输入平台客户ID" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="名" prop="firstName">
        <el-input v-model="formData.firstName" placeholder="请输入名" />
      </el-form-item>
      <el-form-item label="姓" prop="lastName">
        <el-input v-model="formData.lastName" placeholder="请输入姓" />
      </el-form-item>
      <el-form-item label="全名" prop="fullName">
        <el-input v-model="formData.fullName" placeholder="请输入全名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-input v-model="formData.avatar" placeholder="请输入头像" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="formData.gender" placeholder="请选择性别">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_GENDER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-input v-model="formData.birthday" placeholder="请输入生日" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="formData.age" placeholder="请输入年龄" />
      </el-form-item>
      <el-form-item label="语言代码" prop="languageCode">
        <el-input v-model="formData.languageCode" placeholder="请输入语言代码" />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入货币代码" />
      </el-form-item>
      <el-form-item label="时区" prop="timezone">
        <el-input v-model="formData.timezone" placeholder="请输入时区" />
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="formData.customerType" placeholder="请选择客户类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="customerLevel">
        <el-select v-model="formData.customerLevel" placeholder="请选择客户等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="税号" prop="taxNumber">
        <el-input v-model="formData.taxNumber" placeholder="请输入税号" />
      </el-form-item>
      <el-form-item label="营业执照号" prop="businessLicense">
        <el-input v-model="formData.businessLicense" placeholder="请输入营业执照号" />
      </el-form-item>
      <el-form-item label="注册来源" prop="registrationSource">
        <el-input v-model="formData.registrationSource" placeholder="请输入注册来源" />
      </el-form-item>
      <el-form-item label="注册IP" prop="registrationIp">
        <el-input v-model="formData.registrationIp" placeholder="请输入注册IP" />
      </el-form-item>
      <el-form-item label="注册时间" prop="registrationTime">
        <el-date-picker
          v-model="formData.registrationTime"
          type="date"
          value-format="x"
          placeholder="选择注册时间"
        />
      </el-form-item>
      <el-form-item label="最后登录时间" prop="lastLoginTime">
        <el-date-picker
          v-model="formData.lastLoginTime"
          type="date"
          value-format="x"
          placeholder="选择最后登录时间"
        />
      </el-form-item>
      <el-form-item label="最后登录IP" prop="lastLoginIp">
        <el-input v-model="formData.lastLoginIp" placeholder="请输入最后登录IP" />
      </el-form-item>
      <el-form-item label="总订单数" prop="totalOrderCount">
        <el-input v-model="formData.totalOrderCount" placeholder="请输入总订单数" />
      </el-form-item>
      <el-form-item label="总订单金额" prop="totalOrderAmount">
        <el-input v-model="formData.totalOrderAmount" placeholder="请输入总订单金额" />
      </el-form-item>
      <el-form-item label="总支付金额" prop="totalPaidAmount">
        <el-input v-model="formData.totalPaidAmount" placeholder="请输入总支付金额" />
      </el-form-item>
      <el-form-item label="平均订单金额" prop="avgOrderAmount">
        <el-input v-model="formData.avgOrderAmount" placeholder="请输入平均订单金额" />
      </el-form-item>
      <el-form-item label="最后下单时间" prop="lastOrderTime">
        <el-date-picker
          v-model="formData.lastOrderTime"
          type="date"
          value-format="x"
          placeholder="选择最后下单时间"
        />
      </el-form-item>
      <el-form-item label="信用额度" prop="creditLimit">
        <el-input v-model="formData.creditLimit" placeholder="请输入信用额度" />
      </el-form-item>
      <el-form-item label="已用信用额度" prop="creditUsed">
        <el-input v-model="formData.creditUsed" placeholder="请输入已用信用额度" />
      </el-form-item>
      <el-form-item label="积分余额" prop="pointsBalance">
        <el-input v-model="formData.pointsBalance" placeholder="请输入积分余额" />
      </el-form-item>
      <el-form-item label="累计积分" prop="pointsTotal">
        <el-input v-model="formData.pointsTotal" placeholder="请输入累计积分" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CUSTOMER_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱是否验证" prop="emailVerified">
        <el-radio-group v-model="formData.emailVerified">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机是否验证" prop="phoneVerified">
        <el-radio-group v-model="formData.phoneVerified">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="KYC状态" prop="kycStatus">
        <el-radio-group v-model="formData.kycStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_KYC_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select v-model="formData.riskLevel" placeholder="请选择风险等级">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户标签，逗号分隔" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入客户标签，逗号分隔" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderCustomerApi, OrderCustomerVO } from '@/api/crossborder/ordercustomer'
import { DICT_TYPE, getIntDictOptions, getBoolDictOptions } from '@/utils/dict'

/** 跨境电商客户信息 表单 */
defineOptions({ name: 'OrderCustomerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerNo: undefined,
  platformCustomerId: undefined,
  email: undefined,
  phone: undefined,
  firstName: undefined,
  lastName: undefined,
  fullName: undefined,
  nickname: undefined,
  avatar: undefined,
  gender: undefined,
  birthday: undefined,
  age: undefined,
  languageCode: undefined,
  currencyCode: undefined,
  timezone: undefined,
  customerType: undefined,
  customerLevel: undefined,
  companyName: undefined,
  taxNumber: undefined,
  businessLicense: undefined,
  registrationSource: undefined,
  registrationIp: undefined,
  registrationTime: undefined,
  lastLoginTime: undefined,
  lastLoginIp: undefined,
  totalOrderCount: undefined,
  totalOrderAmount: undefined,
  totalPaidAmount: undefined,
  avgOrderAmount: undefined,
  lastOrderTime: undefined,
  creditLimit: undefined,
  creditUsed: undefined,
  pointsBalance: undefined,
  pointsTotal: undefined,
  status: undefined,
  emailVerified: undefined,
  phoneVerified: undefined,
  kycStatus: undefined,
  riskLevel: undefined,
  tags: undefined,
  remark: undefined,
})
const formRules = reactive({
  customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
  firstName: [{ required: true, message: '名不能为空', trigger: 'blur' }],
  lastName: [{ required: true, message: '姓不能为空', trigger: 'blur' }],
  fullName: [{ required: true, message: '全名不能为空', trigger: 'blur' }],
  customerType: [{ required: true, message: '客户类型不能为空', trigger: 'change' }],
  customerLevel: [{ required: true, message: '客户等级不能为空', trigger: 'blur' }],
  totalOrderCount: [{ required: true, message: '总订单数不能为空', trigger: 'blur' }],
  totalOrderAmount: [{ required: true, message: '总订单金额不能为空', trigger: 'blur' }],
  totalPaidAmount: [{ required: true, message: '总支付金额不能为空', trigger: 'blur' }],
  avgOrderAmount: [{ required: true, message: '平均订单金额不能为空', trigger: 'blur' }],
  creditLimit: [{ required: true, message: '信用额度不能为空', trigger: 'blur' }],
  creditUsed: [{ required: true, message: '已用信用额度不能为空', trigger: 'blur' }],
  pointsBalance: [{ required: true, message: '积分余额不能为空', trigger: 'blur' }],
  pointsTotal: [{ required: true, message: '累计积分不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  emailVerified: [{ required: true, message: '邮箱是否验证不能为空', trigger: 'blur' }],
  phoneVerified: [{ required: true, message: '手机是否验证不能为空', trigger: 'blur' }],
  kycStatus: [{ required: true, message: 'KYC状态不能为空', trigger: 'blur' }],
  riskLevel: [{ required: true, message: '风险等级不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderCustomerApi.getOrderCustomer(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderCustomerVO
    if (formType.value === 'create') {
      await OrderCustomerApi.createOrderCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderCustomerApi.updateOrderCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerNo: undefined,
    platformCustomerId: undefined,
    email: undefined,
    phone: undefined,
    firstName: undefined,
    lastName: undefined,
    fullName: undefined,
    nickname: undefined,
    avatar: undefined,
    gender: undefined,
    birthday: undefined,
    age: undefined,
    languageCode: undefined,
    currencyCode: undefined,
    timezone: undefined,
    customerType: undefined,
    customerLevel: undefined,
    companyName: undefined,
    taxNumber: undefined,
    businessLicense: undefined,
    registrationSource: undefined,
    registrationIp: undefined,
    registrationTime: undefined,
    lastLoginTime: undefined,
    lastLoginIp: undefined,
    totalOrderCount: undefined,
    totalOrderAmount: undefined,
    totalPaidAmount: undefined,
    avgOrderAmount: undefined,
    lastOrderTime: undefined,
    creditLimit: undefined,
    creditUsed: undefined,
    pointsBalance: undefined,
    pointsTotal: undefined,
    status: undefined,
    emailVerified: undefined,
    phoneVerified: undefined,
    kycStatus: undefined,
    riskLevel: undefined,
    tags: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>